import 'dart:convert';

import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';

import 'apis.dart';
import 'logs_interceptors.dart';

typedef Success<T> = Function(T data);
typedef Fail = Function(String msg);

class HttpManager {
  static HttpManager _instance = HttpManager._internal();
  Dio? _dio;

  factory HttpManager() => _instance;

  ///通用全局单例，第一次使用时初始化
  HttpManager._internal() {
    if (null == _dio) {
      _dio = Dio(BaseOptions(
          connectTimeout: 15000,
          contentType: "application/json, text/plain, */*"));
      _dio!.interceptors.add(LogsInterceptors());

      // 证书问题
      (_dio!.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
          (client) {
        client.badCertificateCallback = (cert, host, port) {
          return true;
        };
      };
    }
  }

  static HttpManager getInstance(
      {String? baseUrl, Map<String, String>? headers}) {

    _instance._dio!.options.baseUrl = Apis.apiPrefix;
    if (headers != null) {
      _instance._dio!.options.headers = headers;
    }

    return _instance;
  }

  ///通用的GET请求
  void get(url, {params, Success? success, Fail? fail}) async {
    try {
      Response response = await _dio!.get(url, queryParameters: params);

      if (success != null) {
        success(response.data);
      }
    } on DioError catch (e) {
      if (fail != null) {
        fail(e.message + e.toString());
      }
    }
  }

  Future<dynamic> getF(url, {params}) async {
    try {
      Response response = await _dio!.get(url, queryParameters: params);
      return response.data;
    } on DioError catch (e) {
      return null;
    }
  }

  ///通用的POST请求
  void post<T>(url, {params, Success? success, Fail? fail}) async {
    try {
      Response response = await _dio!
          .post(url, queryParameters: json.decode(json.encode(params)));
      if (success != null) {
        success(response.data);
      }
    } on DioError catch (e) {
      if (fail != null) {
        fail(e.message);
      }
    }
  }
}
